using FreeSql;
using NPinyin;
using Simple.Common.Helpers;
using Simple.Contracts.Contracts;
using Simple.Contracts.Enums.Employee;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Contracts.Models.Common.Page;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using Simple.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Services.Services
{
    /// <summary>
    /// 公司管理服务实现
    /// </summary>
    public class CompanyService : BaseService, ICompanyService
    {
        private readonly ISmsService _msService;
        public CompanyService(FreeSqlCloud freeSqlCloud, CurrentAccount currentAccount, ISmsService msService) : base(freeSqlCloud, currentAccount)
        {
            _msService = msService;
        }

        /// <summary>
        /// 分页获取公司列表
        /// </summary>
        /// <param name="input">公司列表输入参数</param>
        /// <returns>公司分页列表</returns>
        public async Task<Result<PageDto<CompanyDto>>> GetPageList(CompanyListInput input)
        {
            var list = await _simpleFreeSql.Select<Company>()
                    .Where(x => x.IsDelete == 0)
                    .WhereIf(!string.IsNullOrEmpty(input.Name), x => x.Name.Contains(input.Name!))
                    .WhereIf(!string.IsNullOrEmpty(input.Version), x => x.Version.Contains(input.Version!))
                    .WhereIf(input.startTime.HasValue, x => x.CreateTime >= input.startTime!.Value)
                    .WhereIf(input.endTime.HasValue, x => x.CreateTime <= input.endTime!.Value)
                    .Count(out var total)
                    .Page(input.pageNum, input.pageSize)
                    .ToListAsync(x => new CompanyDto()
                    {
                        Address = x.Address,
                        AreaName = x.AreaName,
                        AreaId = x.AreaId,
                        CityId = x.CityId,
                        ProvinceId = x.ProvinceId,
                        CityName = x.CityName,
                        ContactName = x.ContactName,
                        ContactPhone = x.ContactPhone,
                        CreateTime = x.CreateTime,
                        Id = x.Id,
                        Name = x.Name,
                        ProvinceName = x.ProvinceName,
                        UpdateTime = x.UpdateTime,
                        Version = x.Version,
                        VersionExpiryTime = x.VersionExpiryTime,
                    });
            return Result<CompanyDto>.PageSuccess(list, total, input);
        }

        /// <summary>
        /// 保存公司信息
        /// </summary>
        /// <param name="input">保存公司信息输入参数</param>
        /// <returns>公司Id</returns>
        public async Task<Result<string>> Save(CompanySaveInput input)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(input.Name))
                {
                    return Result<string>.FriendlyReminder("请输入公司名称");
                }
                if (string.IsNullOrEmpty(input.Version))
                {
                    return Result<string>.FriendlyReminder("请选择版本");
                }
                if (string.IsNullOrEmpty(input.ContactPhone))
                {
                    return Result<string>.FriendlyReminder("请输入联系人手机号");
                }
                if (string.IsNullOrEmpty(input.ContactName))
                {
                    return Result<string>.FriendlyReminder("请输入联系人姓名");
                }

                // 检查名称是否重复（排除当前ID）
                var isNameExists = await _simpleFreeSql.Select<Company>()
                    .Where(x => x.IsDelete == 0 && x.Name == input.Name && x.Id != (input.Id ?? 0))
                    .AnyAsync();
                if (isNameExists)
                {
                    return Result<string>.FriendlyReminder("公司名称已存在");
                }

                if (input.Id.HasValue && input.Id > 0)
                {
                    // 编辑公司信息
                    await _simpleFreeSql.Update<Company>()
                        .Set(x => x.Name, input.Name)
                        .Set(x => x.Version, input.Version)
                        .Set(x => x.VersionExpiryTime, input.VersionExpiryTime)
                        .Set(x => x.ProvinceId, input.ProvinceId)
                        .Set(x => x.ProvinceName, input.ProvinceName)
                        .Set(x => x.CityId, input.CityId)
                        .Set(x => x.CityName, input.CityName)
                        .Set(x => x.AreaId, input.AreaId)
                        .Set(x => x.AreaName, input.AreaName)
                        .Set(x => x.Address, input.Address)
                        .Set(x => x.ContactPhone, input.ContactPhone)
                        .Set(x => x.ContactName, input.ContactName)
                        .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                        .Set(x => x.UpdateTime, DateTime.Now)
                        .Where(x => x.Id == input.Id.Value && x.IsDelete == 0)
                        .ExecuteAffrowsAsync();

                    return Result<string>.Success(string.Empty);
                }
                else
                {
                    // 新增公司信息
                    var companyEntity = new Company
                    {
                        Name = input.Name,
                        Version = input.Version,
                        VersionExpiryTime = input.VersionExpiryTime,
                        ProvinceId = input.ProvinceId,
                        ProvinceName = input.ProvinceName,
                        CityId = input.CityId,
                        CityName = input.CityName,
                        AreaId = input.AreaId,
                        AreaName = input.AreaName,
                        Address = input.Address,
                        ContactPhone = input.ContactPhone,
                        ContactName = input.ContactName,
                        CreateBy = _currentAccount.EmployeeId,
                        CreateTime = DateTime.Now,
                        UpdateBy = _currentAccount.EmployeeId,
                        UpdateTime = DateTime.Now,
                        IsDelete = 0
                    };
                    var companyId = await _simpleFreeSql.Insert(companyEntity).ExecuteIdentityAsync();

                    // 新增员工
                    var passwordPlaintext = RandomHelper.GenerateNumericPassword(6);
                    var employeeEntity = new Employee()
                    {
                        CompanyId = companyId,
                        Name = input.ContactName,
                        NamePinyin = Pinyin.GetPinyin(input.ContactName),
                        NamePinyinCapitalLetter = Pinyin.GetInitials(input.ContactName),
                        Phone = input.ContactPhone,
                        Password = MD5Helper.GetMd5HashLowercase(passwordPlaintext),
                        PasswordPlaintext = passwordPlaintext,
                        Gender = 0,
                        IdCard = "",
                        Status = (int)EmployeeStatusEnum.启用,
                        Brithday = DateTime.Parse("2000-01-01"),
                        ChineseZodiac = "--",
                        IsAdmin = 1,
                        CreateTime = DateTime.Now,
                        CreateBy = _currentAccount.EmployeeId,
                        UpdateBy = _currentAccount.EmployeeId,
                        UpdateTime = DateTime.Now,
                        IsDelete = 0
                    };
                    var employeeId = await _simpleFreeSql.Insert<Employee>(employeeEntity).ExecuteIdentityAsync();

                    // 新增公司角色
                    var sysVersion = await _simpleFreeSql.Select<SysVersion>().Where(x => x.Name == input.Version).FirstAsync();
                    var versionInitRoleList = sysVersion.InitRole.Split('|').Where(x => x.Contains("√")).ToList();
                    var sysPermission = await _simpleFreeSql.Select<SysPermission>().Where(x => x.Version.Contains(input.Version)).ToListAsync();
                    foreach (var roleName in versionInitRoleList)
                    {
                        /// 新增角色
                        var roelEntity = new Role()
                        {
                            CompanyId = companyId,
                            CreateBy = employeeId,
                            CreateTime = DateTime.Now,
                            IsDelete = 0,
                            Name = roleName.Replace("√", ""),
                            UpdateBy = employeeId,
                            UpdateTime = DateTime.Now,
                        };
                        var roleId = await _simpleFreeSql.Insert<Role>(roelEntity).ExecuteIdentityAsync();

                        // 新增角色权限
                        var rolePermissions = sysPermission.Where(x => x.InitRole.Contains(roleName)).ToList();
                        if (rolePermissions.Any())
                        {
                            var rolePermissionEntitys = new List<RolePermission>();
                            foreach (var permission in rolePermissions)
                            {
                                rolePermissionEntitys.Add(new RolePermission()
                                {
                                    CompanyId = companyId,
                                    CreateBy = employeeId,
                                    CreateTime = DateTime.Now,
                                    IsDelete = 0,
                                    PermissionId = permission.Id,
                                    RoleId = roleId,
                                    SelectedStatus = permission.Type == "功能权限" ? "全选中" : "半选中",
                                    UpdateBy = employeeId,
                                    UpdateTime = DateTime.Now,
                                });
                            }
                            await _simpleFreeSql.Insert<RolePermission>(rolePermissionEntitys).ExecuteAffrowsAsync();
                        }
                    }

                    // 发送验证码
                    await _msService.SendRegisterPassword(employeeEntity.Phone, passwordPlaintext);


                    return Result<string>.Success(passwordPlaintext);
                }
            }
            catch (Exception ex)
            {
                return Result<string>.FriendlyReminder("保存公司信息失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 修改公司版本
        /// </summary>
        /// <param name="input">修改公司版本输入参数</param>
        /// <returns>操作结果</returns>
        public async Task<Result<bool>> UpdateVersion(UpdateCompanyVersionInput input)
        {
            try
            {
                // 验证必填字段
                if (input.CompanyId <= 0)
                {
                    return Result<bool>.FriendlyReminder("请选择公司");
                }
                if (string.IsNullOrEmpty(input.Version))
                {
                    return Result<bool>.FriendlyReminder("请选择版本");
                }

                // 检查公司是否存在
                var company = await _simpleFreeSql.Select<Company>()
                    .Where(x => x.Id == input.CompanyId && x.IsDelete == 0)
                    .FirstAsync();
                if (company == null)
                {
                    return Result<bool>.FriendlyReminder("公司不存在");
                }

                // 修改公司版本
                await _simpleFreeSql.Update<Company>()
                    .Set(x => x.Version, input.Version)
                    .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                    .Set(x => x.UpdateTime, DateTime.Now)
                    .Where(x => x.Id == input.CompanyId)
                    .ExecuteAffrowsAsync();

                return Result<bool>.Success(true);
            }
            catch (Exception ex)
            {
                return Result<bool>.FriendlyReminder("修改公司版本失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 修改公司过期时间
        /// </summary>
        /// <param name="input">修改公司过期时间输入参数</param>
        /// <returns>操作结果</returns>
        public async Task<Result<bool>> UpdateExpiryTime(UpdateCompanyExpiryTimeInput input)
        {
            try
            {
                // 验证必填字段
                if (input.CompanyId <= 0)
                {
                    return Result<bool>.FriendlyReminder("请选择公司");
                }

                // 检查公司是否存在
                var company = await _simpleFreeSql.Select<Company>()
                    .Where(x => x.Id == input.CompanyId && x.IsDelete == 0)
                    .FirstAsync();
                if (company == null)
                {
                    return Result<bool>.FriendlyReminder("公司不存在");
                }

                // 修改公司过期时间
                await _simpleFreeSql.Update<Company>()
                    .Set(x => x.VersionExpiryTime, input.VersionExpiryTime)
                    .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                    .Set(x => x.UpdateTime, DateTime.Now)
                    .Where(x => x.Id == input.CompanyId)
                    .ExecuteAffrowsAsync();

                return Result<bool>.Success(true);
            }
            catch (Exception ex)
            {
                return Result<bool>.FriendlyReminder("修改公司过期时间失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除公司
        /// </summary>
        /// <param name="companyId">公司Id</param>
        /// <returns>操作结果</returns>
        public async Task<Result<bool>> Delete(long companyId)
        {
            try
            {
                // 验证必填字段
                if (companyId <= 0)
                {
                    return Result<bool>.FriendlyReminder("请选择公司");
                }

                // 检查公司是否存在
                var company = await _simpleFreeSql.Select<Company>()
                    .Where(x => x.Id == companyId && x.IsDelete == 0)
                    .FirstAsync();
                if (company == null)
                {
                    return Result<bool>.FriendlyReminder("公司不存在");
                }

                // 执行软删除
                await _simpleFreeSql.Update<Company>()
                    .Set(x => x.IsDelete, 1)
                    .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                    .Set(x => x.UpdateTime, DateTime.Now)
                    .Where(x => x.Id == companyId)
                    .ExecuteAffrowsAsync();

                return Result<bool>.Success(true);
            }
            catch (Exception ex)
            {
                return Result<bool>.FriendlyReminder("删除公司失败：" + ex.Message);
            }
        }
    }
}